package org.fxkj.cloud.uaa.service.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.fxkj.cloud.uaa.service.security.model.token.JwtToken;
import org.fxkj.cloud.uaa.service.security.model.token.JwtTokenFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Description: </p>
 *
 * @author Wei, Wu
 * @create 2024/11/19 9:01
 */
@Component
@RequiredArgsConstructor
public class WXLoginSuccessHandler implements AuthenticationSuccessHandler {
    private final JwtTokenFactory jwtTokenFactory;
    private final ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        JwtToken accessToken = jwtTokenFactory.createAccessToken(securityUser);
        JwtToken refreshToken = jwtTokenFactory.createRefreshToken(securityUser);
        Map<String, String> tokenMap = new HashMap<String, String>();
        tokenMap.put("token", accessToken.getToken());
        tokenMap.put("refreshToken", refreshToken.getToken());
        tokenMap.put("openid", securityUser.getWxOpenid());
        tokenMap.put("newUserFlag", securityUser.getNewUserFlag().toString());
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        objectMapper.writeValue(response.getWriter(), tokenMap);

        // todo 登陆成功日志
        clearAuthenticationAttributes(request);
    }


    /**
     * Removes temporary authentication-related data which may have been stored
     * in the session during the authentication process..
     */
    protected final void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);

        if (session == null) {
            return;
        }

        session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    }
}
